<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button flex felx_align">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
        <div class="guidetext" @click="imgShow = true"><i class="iconfont iconiconfontwenhao1 guide"></i>操作指引</div>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <!-- <el-option label="包名" value="package"></el-option> -->
              <el-option label="批次" value="batch"></el-option>
              <el-option label="归属" value="username"></el-option>
              <!-- <el-option label="应用名称" value="package_name"></el-option> -->
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- 设备归属管理table -->
    <el-table stripe style="width: 100%" :data="tableData" :key="key" border fit highlight-current-row ref="tableDataRef" max-height="545" @sort-change="tableSortCge">
      <el-table-column v-if="colData[0].istrue" min-width="110" align="center" prop="username" label="归属"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="120" align="center" prop="batch" label="批次" sortable="custom"></el-table-column>
      <el-table-column v-if="colData[5].istrue" min-width="160" align="center" prop="usable" label="是否可用">
        <template slot-scope="scope">
          <span v-if="scope.row.usable==1">可用</span>
          <span v-else>不可用</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="160" align="center" prop="package_name" label="应用名称"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="160" align="center" prop="package" label="包名"></el-table-column>
      <el-table-column v-if="colData[4].istrue" min-width="140" align="center" prop="create_time" label="创建时间">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column min-width="150" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getqueryIdAppIcon(scope.row.id)">编辑</el-button>
            <el-button size="mini" @click="deleteShow(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <div>
      <el-dialog title="系统桌面图标可见性管控" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="50%">
        <el-form :model="addForm" ref="ruleForm" :rules="rules" class="diolog_adapt">
          <el-form-item label="批次:" label-width="180px" prop="batch">
            <el-select v-model="addForm.batch" placeholder="请选择批次" class="add_select" multiple filterable>
              <el-option v-for="item in lotoptions" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类型:" label-width="180px" prop="usable">
            <el-radio-group v-model="addForm.usable">
              <el-radio :label="1">可用</el-radio>
              <el-radio :label="-1">不可用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="图标隐藏且功能可用包名:" label-width="180px" v-if="addForm.usable==1">
            <el-button type="primary" size="small" @click="showUsableIcon=true">编辑</el-button>
            <el-input type="textarea" :rows="2" v-model="usableIconText"></el-input>
          </el-form-item>
          <el-form-item label="图标隐藏且功能禁用设置:" label-width="180px" v-if="addForm.usable==-1">
            <el-button type="primary" size="small" @click="showUnusableIcon=true">编辑</el-button>
            <el-input type="textarea" :rows="2" v-model="unusableIconText"></el-input>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

    <div>
      <el-dialog title="系统桌面图标可见性管控" :visible.sync="showUsableIcon" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
        <el-form :model="addForm" ref="ruleForm" class="diolog_adapt">
          <el-form-item label="请选择需隐藏的桌面图标:" label-width="180px">
            <el-select v-model="addForm.usable_package" placeholder="请选择包名" multiple class="add_select" filterable clearable>
              <el-option v-for="(item,index) in appDate" :key="index" :label="item.package_name" :value="item.package"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" style="display: flex; justify-content: center;">
          <el-button @click="usableIconClose" size="mini" round>取 消</el-button>
          <el-button  type="primary" @click="addUsableIcon('ruleForm')" size="mini" round>确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-dialog title="系统桌面图标可见性管控" :visible.sync="showUnusableIcon" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
        <el-form :model="addForm" ref="ruleForm" class="diolog_adapt">
          <el-form-item label="请选择需隐藏的桌面图标:" label-width="180px">
            <el-select v-model="addForm.unusable_package" placeholder="请选择包名" multiple class="add_select" filterable clearable>
              <el-option v-for="(item,index) in appDate" :key="index" :label="item.package_name" :value="item.package"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" style="display: flex; justify-content: center;">
          <el-button @click="unusableIconClose" size="mini" round>取 消</el-button>
          <el-button  type="primary" @click="addUnusableIcon('ruleForm')" size="mini" round>确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-dialog title="系统桌面图标可见性管控" :visible.sync="showEdit" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
        <el-form :model="editForm" ref="editForm"  class="diolog_adapt">
          <el-form-item label="批次:" label-width="180px" prop="batch">
            <el-select v-model="editForm.batch" placeholder="请选择批次" class="add_select" multiple filterable>
              <el-option v-for="item in lotoptions" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="请选择需隐藏的桌面图标:" label-width="180px">
            <el-select v-model="editForm.package" placeholder="请选择包名" multiple class="add_select" filterable clearable>
              <el-option v-for="(item,index) in appDate" :key="index" :label="item.package_name" :value="item.package"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" style="display: flex; justify-content: center;">
          <el-button @click="editFormClose" size="mini" round>取 消</el-button>
          <el-button  type="primary" @click="geteditAppIcon('editForm')" size="mini" round>确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 模板操作图片弹窗 -->
      <div class="component" v-if="imgShow">
        <div class="mbImg"><img src="@/assets/images/snZmgk.png" alt=""></div>
        <div class="masking" @click="imgShow = false"></div>
      </div>
      <!-- 删除弹窗 -->
      <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import { queryAppIcon, addAppIcon, editAppIcon, queryIdAppIcon, deleteAppIcon } from "@/api/deployment.js";
import { querySystemAppPackage } from "@/api/allocation.js";
import deleteDialog from "@/components/deleteDialog";
import { getBatchTwo } from "@/api/equipment.js";
import tableMini from '@/utils/tableMini.js'
export default {
  mixins: [tableMini],
  components: { dynamicTable, deleteDialog },
  data() {
    return {
      checkboxVal: ["归属", "批次", "应用名称", "包名", "创建时间", "是否可用"],
      select: "batch", //搜索条件
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制
      showEdit: false,
      //浏览器专题id
      subjectId: 0,
      //批次下拉选择
      lotoptions: [],
      //table
      tableData: [],
      //添加表单
      addForm: { batch: "", package:"", usable_package:[], unusable_package:[], usable:1},
      editForm: {batch: "", package: "", usable: -1},
      rules: {
        batch: [{ required: true, message: "请选择批次", trigger: "blur" }],
        usable: [{ required: true, message: "请选择类型", trigger: "blur" }]
      },
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), package: undefined, batch: undefined, username: undefined, package_name: undefined, sort: '' },
      appDate: [],
      appMap: new Map(),
      imgShow: false,
      spanArr: [],
      usableIconText: '',
      unusableIconText: '',
      showUsableIcon: false,
      showUnusableIcon:false
    }
  },
  created() {
    this.getTabularData()
    this.getquerySystemAppPackage()
  },
  methods: {
    //删除按钮事件
    deleteEvents() {
      let params = {
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        id: this.deleteDialogs.deleteId
      }
      deleteAppIcon(params).then(res => {
        this.$message.success(res.msg)
        this.getTabularData()
      })
    },
    //获取所有包名
    getquerySystemAppPackage() {
      querySystemAppPackage({ userId: localStorage.getItem("ID") }).then(res => {
        let filters = { package_name: ['我的设备'] }//过滤这些
        let keys = Object.keys(filters)
        this.appDate = res.data.filter(item => keys.every(key => filters[key].indexOf(item[key]) === -1))
        this.appMap = this.appDate.reduce((accumulator, currentValue) => {
          accumulator.set(currentValue['package'], currentValue['package_name']);
          return accumulator;
        }, new Map());
      }).catch(err => {
        this.appDate = []
      })
    },
    //编辑应用图标桌面
    geteditAppIcon(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let editForm = JSON.parse(JSON.stringify(this.editForm))
          editForm.last_ip = sessionStorage.getItem("Ip")
          editForm.userId = localStorage.getItem("ID")
          editForm.batch = this.editForm.batch.toString()
          editForm.package = this.editForm.package.toString()
          editForm.id = this.subjectId
          editAppIcon(editForm).then(res => {
            this.showEdit = false
            this.$message.success(res.msg)
            this.getTabularData()
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    //根据ID获取应用图标桌面
    getqueryIdAppIcon(id) {
      this.showEdit = true
      this.subjectId = id
      this.getBatchTwos()
      queryIdAppIcon({ id: id }).then(res => {
        let data = res.data
        this.editForm.batch = data.batch.split(',')
        this.editForm.usable = Number(data.usable)
        this.editForm.package = data.package.split(',')
      })
    },
    //添加应用图标桌面
    addUsableIcon(formName) {
      if (this.hasCommonElements(this.addForm.unusable_package, this.addForm.usable_package)) {
        this.$message.info("同一包名只能设置为可用或不可用一种状态 请检查是否存在冲突")
        return
      }
      this.addForm.usable_package.forEach((value,index)=> {
        var name = this.appMap.get(value)
        this.usableIconText += name + " "
      })
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.batch = this.addForm.batch.toString()
          addForm.package = this.addForm.usable_package.toString()
          addForm.usable = 1
          addAppIcon(addForm).then(res => {
            this.$message.success(res.msg)
            this.getTabularData()
            this.showUsableIcon = false
            this.dialogFormVisible=false
          }).catch(err => { })
        } else {
          return false;
        }
      });
    },
    addUnusableIcon(formName) {
      if (this.hasCommonElements(this.addForm.unusable_package, this.addForm.usable_package)) {
        this.$message.info("同一包名只能设置为可用或不可用一种状态 请检查是否存在冲突")
        return
      }
      this.addForm.unusable_package.forEach((value,index)=> {
        var name = this.appMap.get(value)
        this.unusableIconText += name + " "
      })
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.batch = this.addForm.batch.toString()
          addForm.package = this.addForm.unusable_package.toString()
          addForm.usable = -1
          addAppIcon(addForm).then(res => {
            this.$message.success(res.msg)
            this.getTabularData()
            this.showUnusableIcon = false
            this.dialogFormVisible=false
          }).catch(err => { })
        } else {
          return false;
        }
      });
    },



    getTabularData() {
      queryAppIcon(this.listQuery).then(res => {
        this.tableData = res.data
        this.total = res.total
      }).catch(err => {
        this.tableData = []
        this.total = 0
      })
    },
    //根据ID获取批次列表
    getBatchTwos() {
      let data = { userId: localStorage.getItem("ID") }
      getBatchTwo(data).then(res => {
        this.lotoptions = res.data
      }).catch(err => {
        this.lotoptions = []
      })
    },
    btnaddBrand() {
      this.getBatchTwos()
      this.showEdit = false
      this.dialogFormVisible = true
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.dialogFormVisible=false
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.addForm = this.$options.data().addForm
        this.usableIconText = this.unusableIconText = ""
      })
    },
    usableIconClose() {
      this.showUsableIcon = false
      this.$nextTick(() => {
        this.addForm.usable_package = []
        this.usableIconText = ""
      })
    },
    unusableIconClose() {
      this.showUnusableIcon = false
      this.$nextTick(() => {
        this.addForm.unusable_package = []
        this.unusableIconText = ""
      })
    },
    editFormClose() {
      this.showEdit = false
      this.$nextTick(() => {
        this.$refs.editForm.resetFields();
        this.editForm = this.$options.data().editForm
      })
    },
    //判断两数组是否有重复元素
    hasCommonElements(arr1, arr2) {
      return new Set([...arr1, ...arr2]).size !== arr1.length + arr2.length;
    },
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 5 || columnIndex === 6) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },

    //表格排序事件
    tableSortCge(column) {
      console.log("这是排序")
      let order = ''
      column.order == "descending" ? order = 'desc' : order = 'asc'
      let sort = [{ field: column.prop, sort: order }]
      this.listQuery.sort = JSON.stringify(sort)
      this.getTabularData()
    },

  }
}
</script>

<style scoped>
/deep/ .el-dialog__header {
  transform-origin: 50% 100%;
  border-bottom: 0.5px solid #e9e9e9;
}
</style>
